﻿using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using com.bodurov.SessionRecovery.Interfaces;

namespace com.bodurov.SessionRecovery
{
    public class SessionRecoverySerializer : ISessionRecoverySerializer
    {
        private readonly IFormatter _formatter = new BinaryFormatter();

        private readonly ISessionRecoveryLogger _logger;

        public SessionRecoverySerializer(ISessionRecoveryLogger logger)
        {
            this._logger = logger;
        }

        public void Serialize(Stream sreamToWriteTo, Hashtable unSerializedData)
        {
            try
            {
                _formatter.Serialize(sreamToWriteTo, unSerializedData);
            }
            catch(SerializationException ex)
            {
                this._logger.Log(TraceLevel.Error,
                    "Error serializing session.\r\n" +
                    "Most likely you try to serialize object that is not marked as serializable."+
                    "\r\n'{0}'\r\n{1}", ex.Message, ex);
                throw;
            }
        }

        public Hashtable Deserialize(Stream sreamToReadFrom)
        {
            try
            {
                return _formatter.Deserialize(sreamToReadFrom) as Hashtable;
            }
            catch (SerializationException ex)
            {
                this._logger.Log(TraceLevel.Error,
                    "Error deserializing session.\r\n" +
                    "Most likely you try to serialize object that is not marked as serializable." +
                    "\r\n'{0}'\r\n{1}", ex.Message, ex);
                throw;
            }
        }
    }
}
